#!/usr/bin/env python3
"""
问题诊断脚本
帮助诊断程序运行慢和plotly报错的问题
"""

import sys
import os
import time
import subprocess
import platform
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

def print_header(title):
    """打印标题"""
    print("\n" + "="*60)
    print(f"🔍 {title}")
    print("="*60)

def check_system_info():
    """检查系统信息"""
    print_header("系统信息")
    
    print(f"🖥️  操作系统: {platform.system()} {platform.release()}")
    print(f"🐍 Python版本: {sys.version}")
    print(f"💾 架构: {platform.architecture()[0]}")
    print(f"🕒 当前时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

def check_python_packages():
    """检查Python包版本"""
    print_header("Python包版本检查")
    
    packages = [
        'fastapi', 'uvicorn', 'plotly', 'pandas', 'numpy',
        'akshare', 'redis', 'sqlalchemy', 'bcrypt', 'jose'
    ]
    
    for package in packages:
        try:
            if package == 'jose':
                # 特殊处理python-jose
                module = __import__(package)
                version = getattr(module, '__version__', '未知版本')
                print(f"✅ python-jose: {version}")
            else:
                module = __import__(package.replace('-', '_'))
                version = getattr(module, '__version__', '未知版本')
                print(f"✅ {package}: {version}")
        except ImportError:
            if package == 'jose':
                print(f"❌ python-jose: 未安装")
            else:
                print(f"❌ {package}: 未安装")
        except Exception as e:
            if package == 'jose':
                print(f"⚠️ python-jose: 检查失败 - {e}")
            else:
                print(f"⚠️ {package}: 检查失败 - {e}")

def check_network_connectivity():
    """检查网络连接"""
    print_header("网络连接检查")
    
    urls = [
        ('cdn.plot.ly', 'Plotly CDN'),
        ('pypi.org', 'PyPI'),
        ('github.com', 'GitHub'),
        ('gitee.com', 'Gitee')
    ]
    
    for url, name in urls:
        try:
            import socket
            socket.setdefaulttimeout(5)
            socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((url, 80))
            print(f"✅ {name} ({url}): 连接正常")
        except Exception as e:
            print(f"❌ {name} ({url}): 连接失败 - {e}")

def check_file_structure():
    """检查文件结构"""
    print_header("文件结构检查")
    
    required_files = [
        'requirements.txt',
        'run.py',
        'backend/app/main.py',
        'frontend/templates/index.html',
        'frontend/templates/dashboard.html'
    ]
    
    for file_path in required_files:
        if os.path.exists(file_path):
            size = os.path.getsize(file_path)
            print(f"✅ {file_path} ({size} bytes)")
        else:
            print(f"❌ {file_path}: 文件缺失")

def check_port_availability():
    """检查端口可用性"""
    print_header("端口检查")
    
    ports = [
        (8000, 'FastAPI服务'),
        (6380, 'Redis服务'),
        (6379, 'Redis默认端口')
    ]
    
    for port, service in ports:
        try:
            import socket
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            result = sock.connect_ex(('localhost', port))
            sock.close()
            
            if result == 0:
                print(f"⚠️ 端口 {port} ({service}): 已被占用")
            else:
                print(f"✅ 端口 {port} ({service}): 可用")
        except Exception as e:
            print(f"❌ 端口 {port} ({service}): 检查失败 - {e}")

def check_memory_usage():
    """检查内存使用"""
    print_header("内存使用检查")
    
    try:
        import psutil
        
        # 系统内存
        memory = psutil.virtual_memory()
        print(f"💾 总内存: {memory.total / (1024**3):.1f} GB")
        print(f"💾 可用内存: {memory.available / (1024**3):.1f} GB")
        print(f"💾 内存使用率: {memory.percent}%")
        
        # 当前进程
        process = psutil.Process()
        print(f"🔄 当前进程内存: {process.memory_info().rss / (1024**2):.1f} MB")
        
    except ImportError:
        print("⚠️ psutil未安装，无法检查内存使用")
    except Exception as e:
        print(f"❌ 内存检查失败: {e}")

def test_plotly_functionality():
    """测试Plotly功能"""
    print_header("Plotly功能测试")
    
    try:
        import plotly.graph_objects as go
        import plotly
        
        print(f"✅ Plotly版本: {plotly.__version__}")
        
        # 创建简单图表测试
        fig = go.Figure()
        fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6], name='测试'))
        
        # 转换为JSON测试
        json_data = fig.to_json()
        print("✅ 图表创建和JSON转换: 正常")
        
        # 测试图表大小
        json_size = len(json_data)
        print(f"📊 测试图表JSON大小: {json_size} bytes")
        
        if json_size > 100000:  # 100KB
            print("⚠️ 图表数据较大，可能影响性能")
        
    except Exception as e:
        print(f"❌ Plotly测试失败: {e}")

def test_api_endpoints():
    """测试API端点"""
    print_header("API端点测试")
    
    try:
        import requests
        
        base_url = "http://localhost:8000"
        endpoints = [
            "/health",
            "/api/stock/stocks",
            "/api/realtime/status",
            "/api/market/status"
        ]
        
        for endpoint in endpoints:
            try:
                start_time = time.time()
                response = requests.get(f"{base_url}{endpoint}", timeout=10)
                end_time = time.time()
                
                duration = (end_time - start_time) * 1000
                status = "✅" if response.status_code == 200 else "❌"
                
                print(f"{status} {endpoint}: {response.status_code} ({duration:.0f}ms)")
                
                if duration > 5000:  # 5秒
                    print(f"    ⚠️ 响应时间过长: {duration:.0f}ms")
                
            except requests.exceptions.ConnectionError:
                print(f"❌ {endpoint}: 服务器未运行")
            except requests.exceptions.Timeout:
                print(f"❌ {endpoint}: 请求超时")
            except Exception as e:
                print(f"❌ {endpoint}: {e}")
                
    except ImportError:
        print("⚠️ requests未安装，无法测试API")

def generate_performance_report():
    """生成性能报告"""
    print_header("性能优化建议")
    
    suggestions = [
        "🚀 使用SSD硬盘提升I/O性能",
        "💾 确保至少4GB可用内存",
        "🌐 使用稳定的网络连接",
        "🔧 定期清理浏览器缓存",
        "📊 限制图表数据点数量（<100个）",
        "⚡ 使用现代浏览器（Chrome、Firefox、Edge）",
        "🔄 启用Redis缓存加速数据访问",
        "📱 关闭不必要的后台程序"
    ]
    
    for suggestion in suggestions:
        print(suggestion)

def main():
    """主函数"""
    print("🔧 股票分析平台 - 问题诊断工具")
    print(f"诊断时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 执行所有检查
    check_system_info()
    check_python_packages()
    check_network_connectivity()
    check_file_structure()
    check_port_availability()
    check_memory_usage()
    test_plotly_functionality()
    
    # 如果服务器在运行，测试API
    try:
        import requests
        requests.get("http://localhost:8000/health", timeout=2)
        test_api_endpoints()
    except:
        print_header("API端点测试")
        print("⚠️ 服务器未运行，跳过API测试")
        print("💡 请先运行: python run.py")
    
    generate_performance_report()
    
    print_header("诊断完成")
    print("📋 如果发现问题，请根据上述信息进行修复")
    print("🔧 运行性能修复: python performance_fix.py")
    print("🚀 启动服务器: python run.py")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n⚠️ 诊断被中断")
    except Exception as e:
        print(f"\n❌ 诊断过程出错: {e}")
        import traceback
        traceback.print_exc()
